import type { IUserInfoVo } from '@/api/types/login'
import type { UserInfo } from '@/service/app'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import {
  getUserInfo as _getUserInfo,
  login as _login,
  logout as _logout,
  wxLogin as _wxLogin,
  getWxCode,
} from '@/api/login'
import { userControllerLogin } from '@/service/app'
import { toast } from '@/utils/toast'

// 初始化状态
const userInfoState: UserInfo = {
  id: 0,
  username: '',
  avatar: '',
  password: '',
  phone: '',
  role: '',
  createdAt: '',
  updatedAt: '',
  openid: '',
}

export const useUserStore = defineStore(
  'user',
  () => {
    // 定义用户信息
    const userInfo = ref<UserInfo>({ ...userInfoState })
    // 设置用户信息
    const setUserInfo = (val: UserInfo) => {
      userInfo.value = val
    }

    // 删除用户信息
    const removeUserInfo = () => {
      userInfo.value = { ...userInfoState }
      uni.removeStorageSync('userInfo')
      uni.removeStorageSync('token')
    }
    /**
     * 获取用户信息
     */
    const getUserInfo = async () => {
      const res = await _getUserInfo()
      const userInfo = res.data
      setUserInfo(userInfo)
      uni.setStorageSync('userInfo', userInfo)
      return res
    }
    /**
     * 用户登录
     * @param credentials 登录参数
     * @returns R<IUserLogin>
     */
    const login = async (credentials: {
      username: string
      password: string
      code: string
      uuid: string
    }) => {
      const res = await _login(credentials)
      console.log('登录信息', res)
      toast.success('登录成功')
      await getUserInfo()
      return res
    }

    /**
     * 退出登录 并 删除用户信息
     */
    const logout = async () => {
      _logout()
      removeUserInfo()
    }
    /**
     * 微信登录
     */
    const wxLogin = async () => {
      // 获取微信小程序登录的code
      const { code } = await getWxCode()
      const res = await userControllerLogin({ body: { code } })

      // 微信登录成功后，更新store中的用户信息
      if (res.success && res.data) {
        setUserInfo(res.data) // 调用setUserInfo更新store
        uni.setStorageSync('userInfo', res.data) // 同步到本地存储
      }

      return res
    }

    // 新增：判断是否已登录（基于用户信息）
    const hasLoginInfo = () => {
      // 核心逻辑：判断用户信息中是否存在有效的标识（如id > 0 或 username非空）
      // 可根据你的业务选择判断条件（两者选其一或结合）
      return userInfo.value.id > 0 || userInfo.value.username !== ''
    }

    return {
      userInfo,
      login,
      wxLogin,
      getUserInfo,
      logout,
      hasLoginInfo,
      removeUserInfo,
    }
  },
  {
    persist: true,
  },
)
